#pragma once
#include <semaphore.h>
#include <vector>
#include <pthread.h>

static const int defaultnum = 5;

template <typename T>
class RingQueue
{
private:
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int cap = defaultnum)
        : _ringqueue(cap), _cap(cap)
    {
        sem_init(&_cdata_sem, 0, 0);
        sem_init(&_pspace_sem, 0, cap);
        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }
    void push(const T &in)
    {
        // 先申请信号量再加锁--1.信号量的申请是原子的 2.可以支持申请锁和申请信号量并行
        P(_pspace_sem); // 保证生产者和消费者之间的互斥和同步

        Lock(_p_mutex); // 保证生产者和生产者之间的互斥关系
        _ringqueue[_p_idx++] = in;
        _p_idx %= _cap;
        Unlock(_p_mutex);

        V(_cdata_sem);
    }
    void pop(T *out)
    {
        P(_cdata_sem);
        
        Lock(_c_mutex);
        *out = _ringqueue[_c_idx++];
        _c_idx %= _cap;
        Unlock(_c_mutex);

        V(_pspace_sem);
    }
    ~RingQueue()
    {
        sem_destroy(&_cdata_sem);
        sem_destroy(&_pspace_sem);
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }

private:
    std::vector<T> _ringqueue;
    int _cap;
    size_t _p_idx;
    size_t _c_idx;
    sem_t _cdata_sem;
    sem_t _pspace_sem;
    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};